#include <Arduino.h>
#include <Print.h>
#include <SPI.h>
#include <TFT_eSPI.h>
#include <stdio.h>
#include <string.h>
#include <ArduinoJson.h>  //Json库
#include <lvgl.h>

#include "DHT.h"
#include "img.h"
#include "weather.h"
#include "buzzer.h"
#include "touch.h"
#include "Gettime.h"
/**********Function declear*******************/
double get_tempreture();
double get_humidity();
void link_DHT();
/********************const*************************/
const char *ssid = "radar";
const char *password = "88888888";
const char* host = "api.seniverse.com";//天气服务器网址

/***************define***************************/
#define DHTTYPE DHT11 // 定义传感器类似 DHT11
#define DHTPIN 2 //宏定义DHT数据接口，编译时DHTPIN会替换成2

/***************variable***********************/
extern int currentHour;
extern int currentMinute;
extern int weekDay;

extern int year;
extern int month;
extern int day;
extern int week;

String time_arr = "time: ";
String day_arr = "";
String weekDay_arr = "";
String Tem_arr = "";
String Hum_arr = "";

String now_address="",now_weather="",now_temperature="";//用来存储报文得到的字符串

hw_timer_t *timer = NULL;
/*********************class delearation**************************/
DHT dht(DHTPIN, DHTTYPE);//声明 dht 函数
TFT_eSPI tft = TFT_eSPI();

/*********************Interrupt Function************************/
int i = 0;//the index of pictures
int FALG_timIT = 0;

void IRAM_ATTR onTimer(){
  FALG_timIT = 1;
}
/*********************Setup Function***************************/
void setup() {
  Serial.begin(115200);

  tft.init();
  tft.fillScreen(TFT_BLACK);

  timer = timerBegin(0,80,true);
  timerAttachInterrupt(timer,&onTimer,true);
  timerAlarmWrite(timer,1000000,true);
  timerAlarmEnable(timer);

  //imerAlarmDisable(timer);

  //连接wifi
  WiFi.begin(ssid, password);
  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }

  Serial.println("WiFi connected"); //连接成功
  Serial.print("IP address: ");    //打印IP地址
  Serial.println(WiFi.localIP());

  time_init();

  Serial.println("DHT22 sensor!");
  dht.begin();
}

void loop() {
  if(FALG_timIT){
  FALG_timIT = 0;
  }

  tft.fillScreen(TFT_BLACK);
  tft.setCursor(10,10,2);
  tft.setTextColor(TFT_WHITE);
  time_arr.concat(currentHour);//time:hour
  time_arr.concat(":");//time"hour:
  time_arr.concat(currentMinute);//time: hour:min
  tft.println(time_arr);
  time_arr = "time: ";

  tft.setCursor(10,30,1);
  tft.setTextColor(TFT_WHITE);
  day_arr.concat(year);//year
  day_arr.concat("-");//year-
  day_arr.concat(month);//year-month
  day_arr.concat("-");
  day_arr.concat(day);//year-month-day
  tft.println(day_arr);
  day_arr = "";

  tft.setCursor(10,40,1);
  tft.setTextColor(TFT_WHITE);
  if(weekDay == 1){
    weekDay_arr = "Monday";
  }
  else if(weekDay == 2){
    weekDay_arr = "Tuesday";
  }
  else if(weekDay == 3){
    weekDay_arr = "Wednesday";
  }
  else if(weekDay == 4){
    weekDay_arr = "Thursday";
  }
  else if(weekDay == 5){
    weekDay_arr = "Friday";
  }
  else if(weekDay == 6){
    weekDay_arr = "Saturday";
  }
  else if(weekDay_arr = 7){
    weekDay_arr = "Sunday";
  }
  else{
    weekDay_arr = "Happy Day!";
  }
  tft.println(weekDay_arr);
  weekDay_arr = "";

  tft.setCursor(10,30,1);
  tft.setTextColor(TFT_WHITE);
  day_arr.concat(year);//year
  day_arr.concat("-");//year-
  day_arr.concat(month);//year-month
  day_arr.concat("-");
  day_arr.concat(day);//year-month-day
  tft.println(day_arr);
  day_arr = "";

  tft.setSwapBytes(true);
  tft.pushImage(10,55,64,64,Astronaut[i]);
  i+=1;
    if (i > 8){
      i = 0;
    }
  
  tft.setCursor(80,60,1);
  tft.setTextColor(TFT_WHITE);
  Tem_arr.concat(get_tempreture());//tempreture
  Tem_arr.concat(" C");
  tft.println(Tem_arr);
  Tem_arr = "";

  tft.setCursor(80,70,1);
  tft.setTextColor(TFT_WHITE);
  Hum_arr.concat(get_humidity());//tempreture
  Hum_arr.concat(" %");
  tft.println(Hum_arr);
  Hum_arr = "";

  tft.setCursor(80,80,1);
  tft.setTextColor(TFT_WHITE);
  tft.println(now_weather);

  time_updata();

  //创建TCP连接
    WiFiClient client;
    const int httpPort = 80;
    if (!client.connect(host, httpPort))
    {
      Serial.println("connection failed");  //网络请求无响应打印连接失败
      return;
    }
    //URL请求地址
    
    String url ="/v3/weather/now.json?key=S3N412dVeFWZUZ3S3&location=xian&language=en&unit=c";
    //发送网络请求
    client.print(String("GET ") + url + " HTTP/1.1\r\n" +
              "Host: " + host + "\r\n" +
              "Connection: close\r\n\r\n");
    delay(5000);
    //定义answer变量用来存放请求网络服务器后返回的数据
    String answer;
    while(client.available())
    {
      String line = client.readStringUntil('\r');
      answer += line;
    }
    //断开服务器连接
    client.stop();
    Serial.println();
    Serial.println("closing connection");
    //获得json格式的数据
    String jsonAnswer;
    int jsonIndex;
    //找到有用的返回数据位置i 返回头不要
    for (int i = 0; i < answer.length(); i++) {
      if (answer[i] == '{') {
        jsonIndex = i;
        break;
      }
    }
    jsonAnswer = answer.substring(jsonIndex);
    Serial.println();
    Serial.println("JSON answer: ");
    Serial.println(jsonAnswer);

StaticJsonDocument<512> doc;

deserializeJson(doc, jsonAnswer);

JsonObject results_0 = doc["results"][0];

JsonObject results_0_location = results_0["location"];

const char* results_0_location_name = results_0_location["name"]; 

JsonObject results_0_now = results_0["now"];
const char* results_0_now_text = results_0_now["text"]; 
//const char* results_0_now_code = results_0_now["code"]; 
const char* results_0_now_temperature = results_0_now["temperature"];
now_address = results_0_location_name;
now_weather = results_0_now_text;
now_temperature = results_0_now_temperature;
Serial.print("Now address:");
Serial.println(now_address);
Serial.print("Now weather:");
Serial.println(now_weather);
Serial.print("Now temperature:");
Serial.println(now_temperature);

delay(2000);
}

/********************************Function Content**********************************************************************/

double get_tempreture(){
  return dht.readTemperature();
}

double get_humidity(){
  return dht.readHumidity();
}

void link_DHT(){
  double h = dht.readHumidity();
  double t = dht.readTemperature();

  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
  }
  else{
    Serial.print("Humidity: ");
    Serial.print(h);
    Serial.print(" %t");
    Serial.print("Temperature: ");
    Serial.print(t);
    Serial.println(" *C ");
  }
}
